
#ifdef __PHYSICS_INTERNAL__

#include "pmodel.h"

using namespace WtfEngine;
using namespace PhysicalModels;

/**
 * Sphere physical model - based on Dan's code.
 **/
Sphere::Sphere(tScalar radius, unsigned detail)
	: PhysicalModel(radius)
{
	int hsections, vsections;
	int i, j;
	
	tScalar h_angle, v_angle, old_s_radius, s_radius, old_s_height, s_height;

	
	hsections = vsections = 4 * (detail + 1);
	
	mzLocalVertex = new tVector[hsections * vsections];
	double *xtmp = new double[hsections];
	double *ytmp = new double[hsections];

	for(j = 0; j < hsections; ++j) {
		h_angle = ((tScalar)j/(tScalar)hsections)*2*M_PI;
		xtmp[j]= cos(h_angle);
		ytmp[j] = sin(h_angle);
	}	

	s_height = -radius;
	s_radius = 0.0;

	for(i = 0; i < vsections; ++i) {
		old_s_height = s_height;
		old_s_radius = s_radius;

		v_angle = ((tScalar)i/(tScalar)vsections)*M_PI;
		s_radius = radius*sin(v_angle);
		s_height = radius*cos(v_angle);

		for (j = 0; j < hsections; ++j) {
			int k = (j+1) % hsections;
			
			mzLocalVertex[(i * hsections) + j] = 
					(tVector(xtmp[j]*old_s_radius, old_s_height, ytmp[j]*old_s_radius)
					+ tVector(xtmp[k]*old_s_radius, old_s_height, ytmp[k]*old_s_radius)
					+ tVector(xtmp[k]*s_radius, s_height, ytmp[k]*s_radius)
					+ tVector(xtmp[j]*s_radius, s_height, ytmp[j]*s_radius)) / 4;
		}
	}
	
	this->Create(hsections * vsections);
	
	delete [] ytmp;
	delete [] xtmp;
};

#endif
